package ccb.ygqd.inspur.idcard;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;

import com.ccb.stm.CCBStmCallBack;
import com.siecomzg.bean.IdentityInfoBean;
import com.siecomzg.constconfig.ErrorDefine;
import com.siecomzg.tool.ByteTool;
import com.siecomzg.tool.FileUnits;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.SiecomDevice;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import ccb.ygqd.inspur.common.ConstHF;


public class Idcard  {
    private static final String TAG = Idcard.class.getSimpleName();
    private Context mContext = null;
    public Idcard(Context context){
        mContext = context;
        if (TextUtils.isEmpty(mTimeOut)) mTimeOut = "20";


    }
    /**
     *
     * @param iFlag 是否生成复印件标志
     * @param strPhotoPath 头像图片存放路径
     * @param strPic1Path 复印件正面图路径
     * @param strPic2Path 复印件反面图路径
     * @param strTimeout 读二代证超时间隔   默认20秒；其它正整数
     * @return
     */
    public String[] getIDFullInfo(int iFlag, final String strPhotoPath, String strPic1Path, String strPic2Path, int strTimeout){
        int timeOut = strTimeout;
        timeOut = Math.max(timeOut,10);
        final String ret[] = new String[]{"","","",""};

        if (!SiecomDevice.isConnected){
            ret[0] = ConstHF.ERR_NOT_CONN;
            ret[1] = ConstHF.ERR_DEV_ONT_CONN;
            return ret;
        }
        final CountDownLatch latch = new CountDownLatch(1);
        ret[0] = ConstHF.ERR_SUCCESS;
        SiecomDevice.readIdentityCard(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                LogUtil.e(TAG,"code == " + code + " ---- " + msg);
                ret[0] = ConstHF.ERR_IDC_READ_FAIL; // 读取错误

                if (code == ErrorDefine.ID_TIMEOUT){
                    ret[0] = ConstHF.ERR_TIME_OUT;
                    ret[1] = ErrorDefine.getErrorDescribe(ErrorDefine.ID_TIMEOUT);
                }
                if (code == ErrorDefine.ID_CANCEL_READ){
                    ret[0] = ConstHF.ERR_USER_CANCEL;
                    ret[1] = ErrorDefine.getErrorDescribe(ErrorDefine.ID_CANCEL_READ);
                }
                latch.countDown();
            }

            @Override
            public void onSuccess(Bundle bundle) {

                IdentityInfoBean bean = bundle.getParcelable("data");

                if (!TextUtils.isEmpty(strPhotoPath)){
                   boolean isSuc =  FileUnits.saveImage(bean.icon,strPhotoPath);
                   LogUtil.e(TAG,"isSuc == " + isSuc);
                }

                String orgTxt = bundle.getString("orgData");
                LogUtil.e(TAG,"" + bean.toString() + "\n orgText == " + orgTxt);
                String fingerBase64 = "";
                if (!TextUtils.isEmpty(bean.fingerStr)){
                    fingerBase64 = Base64.encodeToString(ByteTool.hexStr2Bytes(bean.imageStr),Base64.NO_WRAP); //建行要求No_WRAP格式
                }
                LogUtil.e(TAG,"" + fingerBase64);
                ret[0] = ConstHF.ERR_SUCCESS;
                ret[1] = orgTxt;
                ret[2] = fingerBase64;
                latch.countDown();
            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        },timeOut * 1000,1,false);
        try {
            latch.await(timeOut + 2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ret;
    }


    //    Common公共模块（移动外设）
//    本部分定义移动外设的公用接口，包括获取设备状态、复位设备。
//    各模块的定义如下：
//    密码键盘：PIN
//    非接触式IC卡：ICC
//    接触式IC卡：IC1（原为CDB）。
//    发卡箱：CDB
//    指纹仪：FIG
//    电子签名：YGB
//    磁条刷卡器：RDC
//    二代证：IDC
//    居民指纹仪：CFG

    /**
     *
     * @param strEventName 该参数为空或者null时，表示注册该模块的所有事件；有具体值时，表示只注册该模块的具体事件。
     * @param strTimeout 非负整数，事件监听的超时间隔；为0时表示一直监听
     * @param callBack 实现回调函数接口的类实例
     */

    public String mEventName ;
    public String mTimeOut;
    public CCBStmCallBack mCallBack;
    void registEvent(String strEventName, String strTimeout, CCBStmCallBack callBack){
        mEventName = strEventName;
        mTimeOut = strTimeout;
        mCallBack = callBack;
    }

}
